
#include "SQLiteAutoLock.h"

/** SQLite auto lock constructor with reference counting around the
 * database mutex. The SQLiteLockCounter constructor also must here
 * increment its reference count without locking the mutex, so all
 * constructors both copy and otherwise increment the count
 * consistently.
 * 
 * @param idbmutex The SQLite database mutex pointer. */
SQLiteAutoLock::SQLiteAutoLock(sqlite3_mutex *idbmutex)
{
   lockpntr = new SQLiteLockCounter(idbmutex);
}

/** Destructor around the reference counting database mutex class.  As
 * a side-effect the reference count is decremented. */
SQLiteAutoLock::~SQLiteAutoLock()
{
   deleteAtReferenceCountZero();
}

/** Copy constructor for the auto lock, reference counting to lock and
 * unlock on zero. Increments the reference count for each copy.
 * 
 * @param o The other instance. */
SQLiteAutoLock::SQLiteAutoLock(const SQLiteAutoLock &o)
{
   copy(o);
}

/** Copy assignment operator for the auto lock, reference counting to
 * lock and unlock on zero. This also increments the reference count.
 * 
 * @param o The other instance.
 * 
 * @return This instance. */
SQLiteAutoLock &SQLiteAutoLock::operator=(const SQLiteAutoLock &o)
{
   copy(o);
   return *this;
}

/** If the mutex exists and the reference count is zero then leave the
 * mutex. */
void SQLiteAutoLock::deleteAtReferenceCountZero()
{
   if ((lockpntr->decrementReferenceCount() == 0) && (lockpntr))
   {
      delete lockpntr;
      lockpntr = NULL;
   }
}

/** Copy the mutex and increment the reference count.
 * 
 * @param o The other instance. */
void SQLiteAutoLock::copy(const SQLiteAutoLock &o)
{
   lockpntr = o.lockpntr;
   lockpntr->incrementReferenceCount();
}
